<script setup lang="ts">
import type { AdminModel } from '@/apis/types/admin'
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import { updateAdminPasswordResetApi } from '@/apis/modules/admin'
import { Message } from '@arco-design/web-vue'

const emit = defineEmits<{
  (event: 'reload'): void
}>()
const visible = defineModel({ default: false })
const loading = defineModel<boolean>('loading', { default: false })

interface IProps {
  id: string | undefined
  password?: string | undefined
}

const record = defineModel<AdminModel>('record', { default: undefined })

const formRef = ref<FormInstance>()

const formData = reactive<IProps>({
  id: '',
  password: '',
})

const rules = computed<Record<string, FieldRule[]>>(() => {
  const res: Record<string, FieldRule[]> = {
    password: [
      {
        required: true,
        validator: passwordValidate,
        message: '请输入6-64个字符，可包含英文字母、数字和标点符号（除空格）',
      },
    ],
  }
  return res
})

async function handleOk() {
  const res = await formRef.value?.validate?.()
  if (!res) {
    try {
      await updateAdminPasswordResetApi({
        id: String(formData.id),
        password: String(formData.password),
      })
      Message.success('重置成功')
      emit('reload')
      return true
    } catch (_: any) {
      return false
    }
  } else {
    return false
  }
}
function handleOpen() {
  return new Promise((resolve) => {
    formData.id = String(record.value?.id)
    formData.password = defaultPassword()
    resolve(true)
  })
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :width="448"
    title="重置密码"
    :loading="loading"
    :before-ok="handleOk"
    :before-open="handleOpen"
    danger
    ok-text="重置"
  >
    <div class="pb-6 pt-2 text-xs text-color-1">
      确定重置该用户密码吗？
    </div>
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      class="pb-2"
    >
      <a-form-item
        field="password"
        label="默认密码"
        validate-trigger="input"
        asterisk-position="end"
        class="mb-0!"
        hide-asterisk
      >
        <a-input-password
          v-model="formData.password"
          placeholder="请输入密码"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style scoped lang="less"></style>
